//
//  BookReadController.m
//  悦读
//
//  Created by dllo on 15/5/23.
//  Copyright (c) 2015年 贾建兴. All rights reserved.
//

#import "BookReadController.h"
#import "SANetWorkingTask.h"
#import "PageView.h"
#import "ReadCollectionViewCell.h"
#import "CatalogController.h"
#import "WZSnakeHUD.h"
@interface BookReadController ()<UICollectionViewDataSource,UICollectionViewDelegate,CatalogControllerDelegate>

@property (nonatomic, retain) UICollectionView *coll;
@property (nonatomic, retain) UINavigationBar *setView;
@property (nonatomic, retain) UINavigationBar *progressView;
@property (nonatomic, retain) UINavigationBar *backgroudView;
@end

@implementation BookReadController

static NSInteger currentPage = 0, fontNum = 17;


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
      
        self.bookReadDic = [NSMutableDictionary dictionary];
        self.itemArray = [NSMutableArray array];
        self.interfaceArray = [NSMutableArray array];
        self.contentDic = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    
}
- (void)dealloc
{
    [_progressView release];
    [_backgroudView release];
    
    [_setView release];
    [_interfaceArray release];
    [_contentDic release];
    [_itemArray release];
    [_bookReadDic release];
    [_coll release];
    [_sourceId release];
    [super dealloc];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
//     self.navigationController.navigationBar.alpha = 0.5f;
    self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];

    self.wantsFullScreenLayout = YES;
    

    self.navigationController.navigationBarHidden = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"3.png"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    UIImage *image = [UIImage imageNamed:@"listDesk4.png"];
    UIImage *bImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:bImage style:UIBarButtonItemStyleDone target:self action:@selector(catalogAction:)];
    [self readData];
    [self createView];
    [self createSetView];
    
   
}

#pragma mark -
#pragma mark 跳转目录界面
- (void)catalogAction:(id)sender
{
    CatalogController *catalog = [[CatalogController alloc] init];
    
    catalog.catalogArray = self.itemArray;
    //设置代理人
    catalog.delegate = self;
//    self.navigationController.navigationBarHidden = YES;
    [self.navigationController pushViewController:catalog animated:YES];
    [catalog release];
    //跳转界面后,阅读界面的导航栏隐藏
}

#pragma mark -
#pragma mark 获取阅读界面数据
- (void)readData
{
    
    NSDictionary *dic = @{@"sourceId":self.sourceId};
    __block BookReadController *bookRead = self;
    //从资源网址获取书籍
    [SANetWorkingTask request:@"http://vip.hentr.com/zhuibook/api/zhuibook/BookSourceForSourceId.do" parmaters:dic block:^(NSDictionary *result) {
        
        NSDictionary *dic = [result objectForKey:@"response"];
        NSDictionary *data = [dic objectForKey:@"ReturnData"];
        NSString *sourceId = [data objectForKey:@"sourceId"];
        NSString *source = [data objectForKey:@"Source"];
        if ([source isEqualToString:@"easou"]) {
            
            [WZSnakeHUD show:@"加载中..."];
            [self performSelector:@selector(getChapterData:) withObject:nil afterDelay:10];
            
            NSArray *array = [sourceId componentsSeparatedByString:@":"];
            
            [bookRead.interfaceArray addObjectsFromArray:array];
            if (array.count == 1) {
                NSInteger num = [source integerValue];
                num++;
                NSString *str = [NSString stringWithFormat:@"%ld", (long)num];
                NSArray *array1 = [str componentsSeparatedByString:@":"];
                [bookRead.interfaceArray addObjectsFromArray:array1];
            }
            
            NSDictionary *chapterDic = @{@"gid":bookRead.interfaceArray[0], @"nid":bookRead.interfaceArray[1], @"size":@"100000", @"cid":@"eef_"};
            //获取章节
            [SANetWorkingTask request:@"http://api.easou.com/api/bookapp/chapter_list.m" parmaters:chapterDic block:^(NSDictionary *result) {
                //数组bookRead.itemArray为章节数组
                [bookRead.itemArray addObjectsFromArray:[result objectForKey:@"items"]];
                
                [bookRead getChapterData:currentPage];
            }];

        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂无数据源" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        

    }];
}

#pragma mark 获取章节内容数据

- (void)getChapterData:(NSInteger)chapterNum
{
    __block BookReadController *bookRead = self;
     NSDictionary *chapterDic = @{@"gid":bookRead.interfaceArray[0], @"nid":bookRead.interfaceArray[1], @"chapter":[bookRead.itemArray[chapterNum] objectForKey:@"chapter_name"], @"cid":@"eef_",@"sort":[bookRead.itemArray[chapterNum] objectForKey:@"sort"]};
    //获取某一章节的具体内容
    [SANetWorkingTask request:@"http://api.easou.com/api/bookapp/chapter.m" parmaters:chapterDic block:^(NSDictionary *result) {
        NSString *content = [result objectForKey:@"content"];
        if (content != nil) {
            [WZSnakeHUD hide];
            [self.contentDic setDictionary:result];
            [self.coll reloadData];
        } 
        
    }];
}

#pragma mark -
#pragma mark 创建集合视图
- (void)createView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 0);
    layout.itemSize = CGSizeMake(self.view.frame.size.width - 10, self.view.frame.size.height);

    self.coll.bounces = NO;
    self.coll = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 20) collectionViewLayout:layout];
    [self.coll registerClass:[ReadCollectionViewCell class] forCellWithReuseIdentifier:@"jia"];
    [self.coll registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    self.coll.contentSize = CGSizeMake(0, self.coll.frame.size.height);
    [self.coll setBackgroundColor:[UIColor whiteColor]];
    self.coll.dataSource = self;
    self.coll.delegate = self;
    [self.view addSubview:self.coll];
    
    [self.coll release];
}


#pragma mark 执行UICollectionView协议里的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemArray.count - (self.itemArray.count - 1);
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        ReadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"jia" forIndexPath:indexPath];
        //给文本视图赋值
        [cell getText:[self.contentDic objectForKey:@"content"] font:fontNum];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [cell addGestureRecognizer:tap];
        [tap release];
        
        return  cell;
    }
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    return cell;
}



#pragma mark -
#pragma mark 手势翻页

- (void)tapAction:(UITapGestureRecognizer *)tap
{
    CGPoint point = [tap locationInView:tap.view];
    //item左面部分进行点击时,翻前一页
    if (point.x < tap.view.frame.size.width / 3) {
        [self prePage1];
    }
    //item右面部分进行点击时,翻后一页
    if (point.x > tap.view.frame.size.width / 3 * 2 && point.x < tap.view.frame.size.width) {
        [self nextPage1];
    }
    //点中间部分时,显示设置页面,进行设置
    if (point.x > tap.view.frame.size.width / 3 && point.x < tap.view.frame.size.width / 3 * 2) {
        if (self.navigationController.navigationBarHidden) {
             self.navigationController.navigationBar.translucent = YES;
            self.navigationController.navigationBarHidden = NO;
            //弹出设置界面
            self.setView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, -144);
//            self.view.alpha = 0.5;
            self.setView.translucent = YES;
//            self.setView.barStyle = UIBarStyleBlackTranslucent;
        } else {
             self.view.alpha = 1;
            self.navigationController.navigationBarHidden = YES;
            self.setView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 144);
        }

        
        
    }
}



#pragma mark 下一页
- (void)nextPage1
{
    currentPage++;
    if (currentPage == self.itemArray.count) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经是最后一章" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        currentPage = self.itemArray.count - 1;
    } else {
        [self getChapterData:currentPage];
        
    }
}

#pragma mark 前一页
- (void)prePage1
{
    currentPage--;
    if (currentPage < 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经是第一章" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        currentPage = 0;
    } else {
        [self getChapterData:currentPage];
        
    }

}

#pragma mark 根据章节目录来得到阅读内容
- (void)readChapter:(NSInteger )chapterNum
{
    self.navigationController.navigationBarHidden = YES;
    [self getChapterData:chapterNum];
    currentPage = chapterNum;
}

#pragma mark -
#pragma mark 创建阅读设置界面
- (void)createSetView
{
    

    self.setView = [[UINavigationBar alloc] initWithFrame:CGRectZero];
    self.setView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
    [self.setView setBackgroundImage:[UIImage imageNamed:@"3.png"] forBarMetrics:UIBarMetricsDefault];
    self.setView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100);
    [self.view addSubview:_setView];
    [_setView release];
    
    //设置阅读进度界面
    self.progressView = [[UINavigationBar alloc] initWithFrame:CGRectZero];
    self.progressView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
    [self.progressView setBackgroundImage:[UIImage imageNamed:@"3.png"] forBarMetrics:UIBarMetricsDefault];
    self.progressView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100);
    [self.view addSubview:_progressView];
    [_progressView release];
    
    
    //更多设置界面
    
    self.backgroudView = [[UINavigationBar alloc] initWithFrame:CGRectZero];
    self.backgroudView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
    [self.backgroudView setBackgroundImage:[UIImage imageNamed:@"3.png"] forBarMetrics:UIBarMetricsDefault];
    self.backgroudView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 150);
    [self.view addSubview:_backgroudView];
    [_backgroudView release];
    
    //设置阅读进度按钮
    UIButton *progressButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 5 , self.view.frame.size.width / 3, 80)];
    
    [progressButton setBackgroundImage:[[UIImage imageNamed:@"pro.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [progressButton addTarget:self action:@selector(progressAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.setView addSubview:progressButton];
    [progressButton release];
    
    //设置按钮
    UIButton *setButton = [[UIButton alloc] initWithFrame:CGRectMake(progressButton.frame.size.width, progressButton.frame.origin.y + 5, progressButton.frame.size.width, progressButton.frame.size.height)];
    [setButton setBackgroundImage:[UIImage imageNamed:@"set.png"] forState:UIControlStateNormal];
    [setButton addTarget:self action:@selector(setAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.setView addSubview:setButton];
    [setButton release];
    
    //背景按钮
    
    UIButton *nightButton = [[UIButton alloc] initWithFrame:CGRectMake(setButton.frame.origin.x + setButton.frame.size.width, setButton.frame.origin.y, setButton.frame.size.width, setButton.frame.size.height)];
    [nightButton setBackgroundImage:[UIImage imageNamed:@"night.png"] forState:UIControlStateNormal];
    [nightButton addTarget:self action:@selector(nightAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.setView addSubview:nightButton];
    [nightButton release];
    
}

- (void)nightAction:(id)sender
{
    
    
}

- (void)setAction:(id)sender
{
    self.navigationController.navigationBarHidden = YES;
    self.setView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 144);
    UILabel *fontLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 80, 30)];
    fontLabel.text = @"字体大小";
    [self.backgroudView addSubview:fontLabel];
    [fontLabel release];
    
    UISlider *fontSlider = [[UISlider alloc] initWithFrame:CGRectMake(fontLabel.frame.size.width + fontLabel.frame.origin.x + 10, 20, self.view.frame.size.width - fontLabel.frame.size.width - fontLabel.frame.origin.x - 20, 30)];
    [fontSlider setBackgroundColor:[UIColor brownColor]];
    [_backgroudView addSubview:fontSlider];
    fontSlider.minimumValue = 15;
    fontSlider.maximumValue = 30;
    [fontSlider addTarget:self action:@selector(fontAction:) forControlEvents:UIControlEventValueChanged];
    [fontSlider release];
    fontSlider.continuous = NO;
    self.backgroudView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, - 194);
    
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20, fontSlider.frame.origin.y + fontSlider.frame.size.height + 10, 60, 60)];
    
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroudView addSubview:button];
}

- (void)buttonAction:(id)sender
{
    
}

- (void)fontAction:(UISlider *)slider
{
    self.backgroudView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 194);
    fontNum = (int) slider.value;
    [self.coll reloadData];
}

//点击阅读进度按钮,进入进度设置界面
- (void)progressAction:(id)sender
{
    self.navigationController.navigationBarHidden = YES;
    self.setView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 144);
   
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 60, 30)];
    label.text = @"进度";
    [self.progressView addSubview:label];
    [label release];
    
    UISlider *proSlider = [[UISlider alloc] initWithFrame:CGRectMake(label.frame.size.width + label.frame.origin.x + 10, 20, self.view.frame.size.width - label.frame.size.width - label.frame.origin.x - 20, 30)];
    [proSlider setBackgroundColor:[UIColor brownColor]];
    [_progressView addSubview:proSlider];
    proSlider.minimumValue = 0;
    proSlider.maximumValue = self.itemArray.count - 1;
    [proSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [proSlider release];
    proSlider.continuous = NO;
    self.progressView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, - 124);
    
}
//根据进度阅读
- (void)sliderAction:(UISlider *)slider
{
    self.view.alpha = 1;
     self.progressView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 100);
        [self getChapterData:(int)slider.value];
    currentPage = (int)slider.value;
}






@end
